<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2017/2/24
 * Time: 16:56
 */

namespace SDXApi\Service;
use SDXApi\Abstracts\TemplateAbstract;
use SDXApi\Model\HomeTemplateCommendModel;


/**
 * Class HomeTemplateRecommendService
 * @package SDXApi\Service
 */
class HomeTemplateRecommendService extends TemplateAbstract
{
    /**
     * @var HomeTemplateCommendModel
     */
    protected $commendModel;

    /**
     * HomeTemplateRecommendService constructor.
     */
    public function __construct()
    {
        $this->commendModel = new HomeTemplateCommendModel();
    }

    /**
	 * Created by Jerry
	 * @param array $stencil
	 * @param int $userId
	 * @param int $wid
	 * @return array
	 */
	public function handle($stencil = array(), $userId = 0, $wid = 8)
	{
	    $cacheName = 'home_template_commend_id_' . $stencil['id'];
	    $data = $this->getCache($cacheName);

	    if (empty($data)) {
            $data = $this->handleCommend($stencil, $userId, $wid);

            if (! empty($data)) {
                $this->cacheData($cacheName, $data, mt_rand(3600, 4200));
            }
        }

        return $data;
	}

    /**
     * @author Jerry
     * @param array $template
     * @param int $userId
     * @param int $wid
     * @return array|bool
     */
    protected function handleCommend($template = array(), $userId = 0, $wid = 8)
    {

        if ($template['commend_orientation'] == 0) {
            $template['commend_orientation'] = 1;
        }

        $category = $this->commendModel->findCommendCategoryByTemplateId($template['id']);

        if (empty($category)) {
            return $template;
        }

        $ids = array();
        foreach ($category as $key => $value) {
            $ids[] = $value['category_id'];
        }

        $idsStr = implode(',', $ids);
        $template['commend_category_ids'] = $idsStr;

        return $template;
    }
}